import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { get, post } from '@/utils/request'

export interface UserInfo {
  id: number
  username: string
  email?: string
  avatar?: string
  role?: string
  permissions?: string[]
}

export interface LoginForm {
  userName: string
  password: string
  captchaCode: string
  captchaId: string
}

export interface CaptchaResponse {
  code: number;
  message: string;
  data?: {
    captchaId: string;
    imageBase64: string;
    createTime?: string;
    expireTime?: string;
  }
}

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>(localStorage.getItem('token') || '')
  const userInfo = ref<UserInfo | null>(null)
  const isLoggedIn = computed(() => !!token.value)
  const loading = ref(false)
  const captchaId = ref<string>('')

  // 获取验证码（只用 swagger 上的接口路径）
  const getCaptcha = async (): Promise<CaptchaResponse> => {
    try {
      const response = await get<CaptchaResponse>('/api/Captcha/GetCaptcha');
      if (response && response.code === 400 && response.data) {
        captchaId.value = response.data.captchaId || ''
        return response;
      } else {
        return {
          code: 500,
          message: response?.message || '获取验证码失败'
        }
      }
    } catch (error: any) {
      console.error('获取验证码失败:', error)
      return {
        code: 500,
        message: error?.message || '获取验证码失败，请稍后重试'
      }
    }
  }

  // 登录
  const login = async (loginForm: LoginForm) => {
    loading.value = true
    try {
      console.log('发送登录请求:', loginForm);
      
      // 使用相对路径，走代理
      const response = await post<any>('/api/Man/Login', loginForm)
      console.log('登录响应:', response);

      if (response && response.code === 200) {
        // 保存token
        if (response.data && response.data.token) {
          token.value = response.data.token
          localStorage.setItem('token', response.data.token)
        }

        // 保存用户信息
        if (response.data && response.data.user) {
          userInfo.value = response.data.user
          localStorage.setItem('userInfo', JSON.stringify(response.data.user))
        }

        return { success: true, data: response.data }
      } else {
        return { 
          success: false, 
          message: response?.massage || response?.message || '登录失败' 
        }
      }
    } catch (error: any) {
      console.error('登录失败:', error)
      return { 
        success: false, 
        message: error?.message || '登录失败，请稍后重试' 
      }
    } finally {
      loading.value = false
    }
  }

  // 登出
  const logout = () => {
    token.value = ''
    userInfo.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }

  // 获取用户信息
  const getUserInfo = async () => {
    if (!token.value) return null
    
    try {
      const response = await get<any>('/api/Man/GetUserInfo')
      if (response && response.success) {
        userInfo.value = response.userInfo
        localStorage.setItem('userInfo', JSON.stringify(response.userInfo))
        return response.userInfo
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果获取用户信息失败，可能是token过期，清除登录状态
      logout()
    }
    return null
  }

  // 初始化
  const init = async () => {
    if (token.value) {
      // 尝试获取用户信息
      const storedUserInfo = localStorage.getItem('userInfo')
      if (storedUserInfo) {
        try {
          userInfo.value = JSON.parse(storedUserInfo)
        } catch (error) {
          console.error('解析用户信息失败:', error)
          localStorage.removeItem('userInfo')
        }
      }
      // 如果没有用户信息，尝试重新获取
      if (!userInfo.value) {
        await getUserInfo()
      }
    }
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    loading,
    captchaId,
    login,
    logout,
    getUserInfo,
    getCaptcha,
    init
  }
}) 